// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("./utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);
// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 101;
// 预测结果
const predictResults = [];

// ✅ 遍历每一期，从第2期开始
allValues.forEach((item, index) => {
  // ✅ 构造窗口参考历史
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (!temp.length) return;

  // ✅ 构建每个号码在窗口内出现的位置（相对位置）
  const numberIndexMap = {}; // 例如：{ '22': [1, 7, 11] }
  temp.forEach((entry, i) => {
    const num = entry.number;
    if (!numberIndexMap[num]) numberIndexMap[num] = [];
    numberIndexMap[num].push(i);
  });

  // ✅ 计算每个号码的平均间隔和当前未出现间隔
  const scoreMap = {};
  allNumbers.forEach((num) => {
    const appearIndices = numberIndexMap[num] || [];

    if (appearIndices.length < 2) {
      scoreMap[num] = -Infinity; // 数据太少，跳过
      return;
    }

    // ✅ 计算出号间隔列表
    const intervals = [];
    for (let i = 1; i < appearIndices.length; i++) {
      intervals.push(appearIndices[i] - appearIndices[i - 1]);
    }

    const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
    const lastAppearIndex = appearIndices[appearIndices.length - 1];
    const notAppearSince = temp.length - 1 - lastAppearIndex;

    // ✅ 若当前未出现间隔 ≈ 平均间隔 ⇒ 评分越高
    const diff = Math.abs(notAppearSince - avgInterval);
    scoreMap[num] = 1 / (diff + 1e-6); // 差值越小，得分越高
  });

  // ✅ 选出评分前 32 个号码
  const selected = Object.entries(scoreMap)
    .sort((a, b) => b[1] - a[1])
    .map(([num]) => num)
    .slice(0, 32);

  // ✅ 输出当前期预测
  //   console.log(`index=${index}, 当前号码=${item.number}`);
  //   console.log(`预测号码:`, selected);

  // 记录预测结果
  predictResults.push(checkAccuracy(selected, item.number));
});



// 计算准确率
const total = predictResults.length;
const correct = predictResults.filter(x => x === 1).length;
const accuracy = total > 0 ? (correct / total * 100).toFixed(2) : 0;

// 计算最大连续错误次数
let maxWrongStreak = 0;
let currentStreak = 0;
predictResults.forEach(res => {
  if (res === 0) {
    currentStreak++;
    if (currentStreak > maxWrongStreak) {
      maxWrongStreak = currentStreak;
    }
  } else {
    currentStreak = 0;
  }
});

// 输出统计结果
console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);

